package com.bwie.filter;

import com.alibaba.nacos.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: zhaijiaqi
 * @Date: 2025/7/18 15:53
 * @Description:
 **/
@Component
public class MyGloBalFilter implements GlobalFilter  {

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        System.out.println("获取参数"+url);
        //白名单
        if(url.contains("/login")||url.contains("/userReg")||url.contains("/sendCode")){
            System.out.println("白名单"+url);
           return chain.filter(exchange);
        }

        //校验token
        String token = request.getHeaders().getFirst("token");
        if(token==null|| StringUtils.isEmpty(token)){
            System.out.println("token不存在"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
          return   response.setComplete();
        }
        String redistoken = redisTemplate.opsForValue().get(token);
        if(redistoken==null|| StringUtils.isEmpty(redistoken)){
            System.out.println("redistoken已过期"+url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return   response.setComplete();
        }
        //续期
        System.out.println("token续期"+url);
        redisTemplate.expire(token,5, TimeUnit.HOURS);

        //放行
        System.out.println("放行"+url);
        return chain.filter(exchange);
    }
}
